<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showDialog">添加分类</el-button>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <!-- 分别是数据、列属性、前面可选框、展开行效果、索引列、索引名称、边框 -->
      <tree-table
        class="treeTable"
        :data="treeTableData"
        :columns="treeTableColumns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
      >
        <!-- template自定义模板列，用在是否有效那一列 -->
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <!-- 定义排序那一列的自定义模板 -->
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag v-if="scope.row.cat_level === 1" type="success">二级</el-tag>
          <el-tag v-if="scope.row.cat_level === 2" type="danger">三级</el-tag>
        </template>
        <!-- 定义操作那一列 -->
        <template slot="control" slot-scope="scope">
          <el-button
            size="small"
            type="info"
            icon="el-icon-edit"
            @click="editCate(scope)"
            >编辑</el-button
          >
          <el-button size="small" type="danger" icon="el-icon-delete"
           @click="deleteCate(scope)"
            >删除</el-button
          >
        </template>
      </tree-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="getCategoriesData.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="getCategoriesData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 点击添加分类弹出框 -->
    <el-dialog title="添加分类" :visible.sync="dialogVisible" width="50%">
      <el-form
        ref="addCateFormRef"
        :rules="addCategoriesRules"
        :model="addCategoriesForm"
        label-width="100px"
        @close="addCateDialogClosed"
      >
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="addCategoriesForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类：">
          <!-- 级联选择器 -->
          <!-- options 用来指定数据源 -->
          <!-- props 用来指定配置对象 -->
          <el-cascader
            v-model="selectedKeys"
            :options="cascaderValue"
            :props="cascaderOptions"
            @change="handleChangeCascader"
            clearable
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 点击编辑按钮 -->
    <el-dialog
      title="编辑名称"
      @close="closeEditDialog"
      :visible.sync="editDialogVisible"
      width="50%"
    >
      <el-form ref="editForm" :model="editForm" label-width="80px">
        <el-form-item label="分类名称">
          <el-input
            v-model="editForm.name"
            :placeholder="clickEditRow.cat_name"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editDialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 请求参数params
      getCategoriesData: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      // 分页器总数据条数
      total: 0,

      // 表格数据
      treeTableData: [],
      // 表格配置
      treeTableColumns: [
        { label: "分类名称", prop: "cat_name" },
        {
          label: "是否有效",
          // 表示将当前列定义模板列
          type: "template",
          // 表示当前这一列使用模板名称(自定义名称)
          template: "isok",
        },
        {
          label: "排序",
          type: "template",
          template: "order",
        },
        { label: "操作", type: "template", template: "control" },
      ],
      // 弹出框是否显示
      dialogVisible: false,
      // 添加分类弹出框表单数据
      addCategoriesForm: {
        // 分类父ID
        cat_name: "",
        // 父子分类id
        cat_pid: 0,
        // 分类层级
        cat_level: 0,
      },
      // 校验规则
      addCategoriesRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
      },

      // 级联选择器
      // 父级分类的列表
      cascaderValue: [],
      // 指定级联选择器的配置对象
      cascaderOptions: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },

      // 选中的父级分类的ID数组
      selectedKeys: [],

      // 编辑弹出框
      editDialogVisible: false,

      // 编辑名称
      editForm: {
        name: "",
      },

      // 点击编辑获取一行的信息并存储起来给关闭编辑弹框函数用
      clickEditRow: {},
    };
  },

  methods: {
    // 获取商品分类数据
    async getCatelist() {
      const { data: res } = await this.$http.get("categories", {
        params: this.getCategoriesData,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类数据失败");
      } else {
        this.treeTableData = res.data.result;
        this.total = res.data.total;
        // console.log(this.treeTableData);
      }
    },
    // 监听pageSize改变
    handleSizeChange(newSize) {
      this.getCategoriesData.pagesize = newSize;
      this.getCatelist();
    },

    // 监听pagenum改变
    handleCurrentChange(newPage) {
      this.getCategoriesData.pagenum = newPage;
      this.getCatelist();
    },
    // 点击添加分类
    showDialog() {
      this.getCategoriesTypeTwo();
      this.dialogVisible = true;
    },
    // 级联选择器改变触发这个函数
    handleChangeCascader() {
      console.log(this.selectedKeys);
      // 如果selectedKeys数组中的length为0则说明选中了父级分类,反之则说明没有选中父级分类
      if (this.selectedKeys.length > 0) {
        // 父级分类的id
        this.addCategoriesForm.cat_pid =
          this.selectedKeys[this.selectedKeys.length - 1];
        // 为当前分类的等级赋值
        this.addCategoriesForm.cat_level = this.selectedKeys.length;
        return;
      } else {
        // 父级分类的id
        this.addCategoriesForm.cat_pid = 0;
        // 为当前分类的等级赋值
        this.addCategoriesForm.cat_level = 0;
      }
    },
    // 获取商品分类数据列表  供级联选择器
    async getCategoriesTypeTwo() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      if (res.meta.status !== 200) {
        return this.$message.error("请求级联数据失败");
      }
      this.cascaderValue = res.data;
      console.log(this.cascaderValue);
    },
    // 弹出框点击确定按钮
    addCate() {
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "categories",
          this.addCategoriesForm
        );

        if (res.meta.status !== 201) return this.$message.error("添加分类失败");

        this.$message.success("添加分类成功");
        this.getCatelist();
        this.dialogVisible = false;
      });
    },
    // 监听对话框的关闭函数
    addCateDialogClosed() {
      // 重置表单
      this.$refs.addCateFormRef.resetFields();
      this.selectedKeys = [];
      this.addCategoriesForm.cat_pid = 0;
      this.addCategoriesForm.cat_level = 0;
    },
    // 点击编辑按钮
    editCate(scope) {
      this.editDialogVisible = true;
      this.clickEditRow = scope.row;
    },
    // 关闭编辑弹出框触发函数
    async closeEditDialog() {
      const { data: res } = await this.$http.put(
        `categories/${this.clickEditRow.cat_id}`,
        {
          cat_name: this.editForm.name,
        }
      );
      // if (res.meta.status !== 200) return this.$message.error("请求编辑失败");
      this.getCatelist();

      // 清空表单缓存数据
      this.editForm.name = "";
    },
    // 删除分类
    async deleteCate(scope){
      const {data:res} = await this.$http.delete(`categories/${scope.row.cat_id}`)
      if(res.meta.status !== 200) return this.$message.error("删除失败")
      this.getCatelist()
    }
  },
  mounted() {
    this.getCatelist();
  },
};
</script>

<style lang="less" scoped>
.treeTable {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}

</style>